package com.gxlevi.math.kmp;

import java.util.Arrays;

public class KMPAlgorithm {
    public static void main(String[] args) {
        String str1 = "硅硅谷 尚硅谷你尚硅 尚硅谷你尚硅谷你尚硅你好";
        String str2 = "尚硅谷你尚硅你";

        int[] next = kmpNext(str2);
        System.out.println("next=" + Arrays.toString(next));
        System.out.println("查询字符串开始索引为:" + kmp(str1, str2));
    }

    //获取到一个字符串(子串)的部分匹配值表
    public static int[] kmpNext(String dest) {
        //创建一个next数组保存部分匹配值
        int[] next = new int[dest.length()];

        for (int i = 2, j = 0; i < dest.length(); i++) {
            //当dest.charAt(i) != dest.charAt(j),需要从next[j-1]获取新的j
            //直到我们发现有dest.charAt(i) == dest.charAt(j)成立才退出
            while (j > 0 && dest.charAt(i - 1) != dest.charAt(j)) {
                j = next[j];
            }
            //当这个条件满足时,部分匹配值就是+1
            if (dest.charAt(i - 1) == dest.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }

    public static int kmp(String str1, String str2) {
        int[] next = kmpNext(str2);
        int j = 0;
        for (int i = 0; i < str1.length(); i++) {
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - str2.length() + 1;
            }
        }
        return -1;
    }
}
